import {ObjectID} from "mongodb";
import {Promise} from 'es6-promise';
import PWSApp from "../../core/app";
import HomeBaseAction from "./act.base";
import {Magics} from "../../core/magics";
import {ModList} from "../../core/types";
import {Request, Response} from "express";
import * as utils from '../../core/utils';
import {RouteType} from "../../core/defines";
import {ErrCode} from "../../core/error.code";
import {MongoColls} from "../../config/mongo";
import FavoriteModel, {
    FavoriteType,
    FavoriteInfo,
} from "../../models/mod.favorite";

export default class FavoriteAction extends HomeBaseAction {

    name() {
        return `${this.app.name}FavoriteAction`;
    }

    private _favorMod: FavoriteModel;

    constructor(app: PWSApp) {
        super(app);
        this._favorMod = new FavoriteModel(this.db.collection(MongoColls.FAVORITE));
    }

    protected _setRoutes() {
        this._setRoot('/api/favor'); //need login
        this._route(RouteType.POST, '/add', this._actAddToFavor);
        this._route(RouteType.POST, '/del', this._actDeleteFavor);
        this._route(RouteType.GET, '/list/:type/:page', this._actGetFavorList);
    }

    private _actAddToFavor(req: Request, res: Response) {

        Promise.resolve().then(() => {
            let sessUser = req.session[Magics.SessUser] || {};
            let {type, src_id, detail} = req.body;
            if (!utils.isObjectId(src_id) || !utils.isBelongToObj(type, FavoriteType)) {
                return Promise.reject({err_code: ErrCode.ArgsInvalid});
            }
            let user_id: ObjectID = utils.toObjectId(sessUser['_id']);
            let src_id: ObjectID = utils.toObjectId(src_id);
            let info:FavoriteInfo = {
                user_id, src_id,
                type: <FavoriteType>utils.toInt(type),
                detail: detail
            };

            return this._favorMod.addToFavorite({user_id, src_id}, info);
        }).then(() => {
            res.send({err_code: ErrCode.Success});
        }).catch((err) => {
            this._errHandler(req, res, err);
        });
    }

    private _actDeleteFavor(req: Request, res: Response) {
        Promise.resolve().then(() => {
            let {type, src_id} = req.body;
            let sessUser = req.session[Magics.SessUser] || {};
            if (!utils.isObjectId(src_id) || !utils.isBelongToObj(type, FavoriteType)
                || !utils.isObjectId(sessUser['_id'])) {
                return Promise.reject({err_code: ErrCode.ArgsInvalid});
            }
            let user_id: ObjectID = utils.toObjectId(sessUser['_id']);
            let match = {src_id: utils.toObjectId(src_id), user_id};
            return this._favorMod.deleteFavorite(match);
        }).then(() => {
            res.send({err_code: ErrCode.Success});
        }).catch((err) => {
            this._errHandler(req, res, err);
        });
    }

    private _actGetFavorList(req: Request, res: Response) {
        Promise.resolve().then(() => {
            let {type, page} = req.params;
            if (!utils.isBelongToObj(type, FavoriteType)) {
                return Promise.reject({err_code: ErrCode.ArgsInvalid});
            }
            let sessUser = req.session[Magics.SessUser] || {};
            let curPage = utils.isNumeric(page) ? utils.toInt(page) : 0;

            let filter = {
                user_id: utils.toObjectId(sessUser['_id']),
                type: <FavoriteType>utils.toInt(type),
                page: curPage > 0 ? curPage : 0,
                limit: 20
            };
            return this._favorMod.getFavorites(filter);
        }).then((data: ModList) => {
            let {limit, curr_page, total_count, records, total_page} = data;
            let result = {
                limit, curr_page, total_count, records, total_page,
                err_code: ErrCode.Success
            };
            res.send(result);
        }).catch((err) => {
            this._errHandler(req, res, err);
        });
    }

}